package com.carkeeper.system.service.impl;

import com.carkeeper.common.utils.Result;
import com.carkeeper.common.utils.StatusCode;
import com.carkeeper.system.dao.RoleDao;
import com.carkeeper.system.pojo.Role;
import com.carkeeper.system.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * @author 周志雄
 * @version 1.0
 * @date 2020/11/24 14:42
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;


    @Override
    public Page<Role> queryByCondition(Map map, int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        Example example = createExample(map);
        return (Page<Role>) roleDao.selectByExample(example);
    }

    @Override
    public List<Role> findAll() {
        return roleDao.selectAll();
    }

    @Override
    public Result delete(Long id) {

        //删除中间关系表
        roleDao.deleteByRoleId(id);
        int i = roleDao.deleteByPrimaryKey(id);

        if (i == 0) {
            return new Result(false, StatusCode.ERROR, "删除失败");
        }

        return new Result(true, StatusCode.OK, "删除成功");
    }

    @Override
    @Transactional
    public Result add(Role role) {
        List<Long> menuIds = role.getMenuIds();

        if (menuIds.size() == 0) {
            throw new RuntimeException("请选择该角色的菜单");
        }

        roleDao.insertRoleReturnId(role);

        for (Long menuId : menuIds) {
            roleDao.insertRoleIdAndMenuId(role.getId(), menuId);
        }

        return new Result(true, StatusCode.OK, "添加角色成功");
    }


    /**
     * 修改角色
     *
     * @param role
     * @return
     */
    @Override
    @Transactional
    public Result update(Role role) {
        List<Long> menuIds = role.getMenuIds();
        if (menuIds.size() == 0) {
            throw new RuntimeException("请选择该角色的菜单");
        }

        roleDao.updateByPrimaryKeySelective(role);
        roleDao.deleteByRoleId(role.getId());
        for (Long menuId : menuIds) {
            roleDao.deleteByRoleId(role.getId());
        }

        return new Result(true, StatusCode.OK, "修改角色成功");
    }

    private Example createExample(Map map) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if (map != null) {
            if (map.get("name") != null) {
                criteria.andLike("name", "%" + map.get("name") + "%");
            }
        }

        return example;
    }
}
